<?php
    /**
     * Created by PhpStorm.
     * User: mybook-lhp
     * Date: 18/9/19
     * Time: 下午4:53
     */

    namespace app\member\model;


    use app\base\model\WalletProductModel;
    use app\common\utils\UtilTree;
    use app\face2market\model\Face2marketRecommendRewardMsgModel;
    use app\face2market\model\RegisterShareLogModel;
    use app\face2market\model\ReleaseLockLogModel;
    use app\face2market\model\WalletProductLockModel;
    use app\payment\model\WalletModel;
    use app\share\model\ShareBuyAwardModel;
    use app\share\model\ShareLogModel;
    use app\share\model\ShareReferrerAwardModel;
    use think\Db;
    use think\Model;

    class CheckDataModel extends Model
    {

        protected $name = 'face2market_member_diffe';

        // 自动写入时间戳
        protected $autoWriteTimestamp = true;

        protected $dateFormat = 'Y/m/d H:s';

        /**
         * 用户资产是否正常
         */
        static public function save_data()
        {

            $MemberModel = MemberModel::where([])->select();

            foreach ($MemberModel as $item)
            {
                static::member_info($item->id);
                $payment_wallet = static::payment_wallet($item->id);
                static::base_wallet_product($item->id);
                static::order($item->id);

                $order       = static::order($item->id);
                $order_limit = static::order_limit($item->id);
                $topup       = static::topup($item->id);
                $withdraw    = static::withdraw($item->id);

                $difference = (($topup['statistics']['amount'] - $order['statistics']['buy_money'] + $order['statistics']['seller_money'] - $withdraw['statistics']['amount'] - $payment_wallet['money'] - $order_limit['statistics']['buy_money']) / 100);
                if (self::where(['member_id' => $item->id])->find())
                {
                    self::where(['member_id' => $item->id])->update([
                        'member_id'   => $item->id,
                        'data'        => json_encode([
                            $topup['statistics']['amount'],
                            $order['statistics']['buy_money'],
                            $order['statistics']['seller_money'],
                            $withdraw['statistics']['amount'],
                            $payment_wallet['money'],
                            $order_limit['statistics']['buy_money']
                        ]),
                        'update_time' => time(),
                        'diffe'       => $difference
                    ]);
                }
                else
                {
                    self::create([
                        'member_id'   => $item->id,
                        'data'        => json_encode([
                            $topup['statistics']['amount'],
                            $order['statistics']['buy_money'],
                            $order['statistics']['seller_money'],
                            $withdraw['statistics']['amount'],
                            $payment_wallet['money'],
                            $order_limit['statistics']['buy_money']
                        ]),
                        'diffe'       => $difference,
                        'create_time' => time(),
                        'update_time' => time(),
                    ]);
                }

            }
        }

        /**
         * 用户信息
         *
         * @param $id
         *
         * @return array|false|\PDOStatement|string|\think\Model
         */
        static public function member_info($id)
        {

            return MemberInfoModel::where(['member_id' => $id])->find();
        }

        /**
         * 用户充值
         *
         * @param $id
         *
         * @return mixed
         */
        static public function payment_wallet($id)
        {

            return WalletModel::where(['member_id' => $id])->find();
        }

        /**
         * 用户资产
         *
         * @param $id
         *
         * @return mixed
         */
        static public function base_wallet_product($id)
        {

            return WalletProductModel::where(['member_id' => $id])->column('product_id as id,product_num');
        }

        static public function base_wallet_product_lock($id)
        {

            $WalletProductLockModel = ReleaseLockLogModel::where(['member_id' => $id])->field('num')->find();
            if (!empty($WalletProductLockModel))
            {
                $data = $WalletProductLockModel['num'];
            }
            else
            {
                $data = 0;
            }
            return $data;
        }

        /**
         * 用户挂单
         *
         * @param $id
         *
         * @return mixed
         */
        static public function order_limit($id)
        {

            $face2market_order_limit       = Db::view('face2market_order_limit',true)//字段
            ->view('member','phone','member.id = face2market_order_limit.member_id','left')//
            ->where(['face2market_order_limit.member_id' => $id])->order('face2market_order_limit.create_time','desc')->paginate(5);
            $data['data']                  = $face2market_order_limit;
            $data['page']                  = $face2market_order_limit->render();
            $data['statistics']            = [
                'buy_money' => Db::name('face2market_order_limit')->field('(residue_number * price) as buy_money')->where([
                    'member_id' => $id,
                    'status'    => 0
                ])->find()['buy_money'],
                'buy_pro'   => Db::name('face2market_order_limit')->where([
                    'member_id' => $id,
                    'status'    => 1
                ])->sum('residue_number'),
            ];
            $data['statistics']['buy_pro'] = floor($data['statistics']['buy_pro'] * 1.1) . '(' . $data['statistics']['buy_pro'] . '+' . floor($data['statistics']['buy_pro'] * 0.1) . ')';

            $data['statistics']['buy_money'] = $data['statistics']['buy_money'] > 0 ? $data['statistics']['buy_money'] : 0;
            return $data;
        }

        /**
         * 用户表
         *
         * @param $id
         *
         * @return array|false|\PDOStatement|string|\think\Model
         */
        static public function member($id)
        {

            $MemberModel = MemberModel::where(['id' => $id])->find();

            UtilTree::config([
                'title' => 'phone',
                'pid'   => 'phone_puid'
            ]);


            return $MemberModel;
        }

        static public function payment_conf($id)
        {

            return PaymentInfoModel::where(['member_id' => $id])->find();
        }

        /**
         * 用户等级
         *
         * @param $id
         *
         * @return mixed
         */
        static public function memberlevel($id)
        {

            $buy_level              = ShareBuyAwardModel::where(['member_id' => $id])->find();
            $referrer_level         = ShareReferrerAwardModel::where(['member_id' => $id])->find();
            $data['buy_level']      = '认购等级：V' . ($buy_level['level'] > 0 ? $buy_level['level'] : 0);
            $data['referrer_level'] = ' 业绩等级：星' . ($referrer_level['level'] > 0 ? $referrer_level['level'] : 0);
            return $data;
        }

        /**
         * 用户交易记录
         *
         * @param $id
         *
         * @return mixed
         */
        static public function order($id)
        {

            $face2market_order = Db::view('face2market_order',true)//字段
            ->view('member m1','phone as buyer','m1.id = face2market_order.buyer_id','LEFT')//
            ->view('member m2','phone as seller','m2.id = face2market_order.seller_id','LEFT')//
            ->where([
                'm2.id'                    => $id,
                'del'                      => 0,
                'face2market_order.status' => 1
            ])->whereOr(['m1.id' => $id])->where(['face2market_order.del' => 0,])//
            ->order('face2market_order.create_time','desc')->paginate(10);
            //            echo json_encode($face2market_order);
            //            exit;
            $data['data']       = $face2market_order;
            $data['page']       = $face2market_order->render();
            $data['statistics'] = [
                'buy_pro'      => Db::name('face2market_order')->where([
                    'buyer_id' => $id,
                    'status'   => 1,
                    'del'      => 0
                ])->sum('number'),
                'buy_money'    => Db::name('face2market_order')->where([
                    'buyer_id' => $id,
                    'status'   => 1,
                    'del'      => 0
                ])->sum('amount'),
                'seller_pro'   => Db::name('face2market_order')->where([
                    'seller_id' => $id,
                    'status'    => 1,
                    'del'       => 0
                ])->sum('number'),
                'seller_money' => Db::name('face2market_order')->where([
                    'seller_id' => $id,
                    'status'    => 1,
                    'del'       => 0
                ])->sum('amount'),
            ];
            if ($data['statistics']['buy_money'])
            {
                $buy_age = round(($data['statistics']['buy_money'] / 100) / $data['statistics']['buy_pro'],5);

            }
            else
            {
                $buy_age = 0;
            }
            if ($data['statistics']['seller_money'])
            {
                $seller_age = round(($data['statistics']['seller_money'] / 100) / $data['statistics']['seller_pro'],5);

            }
            else
            {
                $seller_age = 0;
            }
            $data['statistics']['buy_age']    = $buy_age;
            $data['statistics']['seller_age'] = $seller_age;
            $data['statistics']['seller_pro'] = floor($data['statistics']['seller_pro'] * 1.1) . '(' . $data['statistics']['seller_pro'] . '+' . floor($data['statistics']['seller_pro'] * 0.1) . ')';
            return $data;
        }

        /**
         * 充值
         *
         * @param $id
         *
         * @return mixed
         */
        static public function topup($id)
        {

            $payment_pay        = Db::view('payment_pay',true)//字段
            ->view('member','phone','member.id = payment_pay.member_id','left')//
            ->where([
                'payment_pay.member_id' => $id,
                'payment_pay.status'    => 1
            ])->order('payment_pay.create_time','desc')->paginate();
            $data['data']       = $payment_pay;
            $data['page']       = $payment_pay->render();
            $data['statistics'] = [
                'amount' => Db::name('payment_pay')->where(['member_id' => $id,'status' => 1])->sum('money'),
            ];
            $data['statistics'] = $data['statistics'] > 0 ? $data['statistics'] : 0;
            return $data;
        }

        /**
         * 用户提现
         *
         * @param $id
         *
         * @return mixed
         */
        static public function withdraw($id)
        {

            $payment_withdraw = Db::view('payment_withdraw',true)//字段
            ->view('member','phone','member.id = payment_withdraw.member_id','left')//
            ->where([
                'payment_withdraw.member_id' => $id
            ])->whereIn('payment_withdraw.status',[0,2,4])->order('payment_withdraw.create_time','desc')->paginate();

            $data['data']       = $payment_withdraw;
            $data['page']       = $payment_withdraw->render();
            $data['statistics'] = [
                'amount' => Db::name('payment_withdraw')->where(['member_id' => $id])->whereIn('status',[
                    0,
                    2,
                    4
                ])->sum('up_amount_money'),
            ];

            $data['statistics']['amount'] = $data['statistics']['amount'] > 0 ? $data['statistics']['amount'] : 0;
            return $data;
        }

        /**
         * 分享
         *
         * @param $id
         *
         * @return mixed
         */
        static public function shareReward($id)
        {

            $RegisterShareLogModel = RegisterShareLogModel::where(['member_id_puid' => $id])->field('sum(share_obtain_num) as reward')->find();
            $MemberModel           = MemberModel::where(['phone_puid' => $id])->field('count(id) as num')->find();
            //            face2market_recommend_reward_msg
            $buy_num           = Face2marketRecommendRewardMsgModel::recommend_msg_count($id);
            $rewards           = Face2marketRecommendRewardMsgModel::recommend_msg_sum($id);
            $group_rewards     = Face2marketRecommendRewardMsgModel::recommend_msg_group_sum($id);
            $buy_reward_refer  = ShareLogModel::where([
                'rewarder_id' => $id,
                'type'        => 1
            ])->field('sum(reward_number) as reward_number')->find();
            $rerr_reward_refer = ShareLogModel::where([
                'rewarder_id' => $id,
                'type'        => 2
            ])->field('sum(reward_number) as reward_number')->find();
            $rewards           = $rewards > 0 ? $rewards : 0;
            $group_rewards     = $group_rewards > 0 ? $group_rewards : 0;
            $reward            = $RegisterShareLogModel['reward'] > 0 ? ($RegisterShareLogModel['reward'] / 100) : 0;
            $reward_number     = $buy_reward_refer['reward_number'] > 0 ? $buy_reward_refer['reward_number'] : 0;
            $rerr_reward       = $rerr_reward_refer['reward_number'] > 0 ? $rerr_reward_refer['reward_number'] : 0;
            $buy_num           = $buy_num > 0 ? $buy_num : 0;
            $data['num']       = $MemberModel['num'] > 0 ? $MemberModel['num'] : 0;

            $data['reward']        = '购买(' . $rewards . '+' . $group_rewards . '+' . $reward_number . '+' . $rerr_reward . ') +分享：' . $reward . '=' . ($reward + $group_rewards + $rewards + $reward_number + $rerr_reward);
            $data['buy_num']       = $buy_num;
            $data['reward_number'] = $reward_number;

            return $data;
        }

        /**
         * 验证数据
         *
         * @return array|string
         */
        static public function check_error()
        {

            $list = Db::view('face2market_member_diffe fmd','diffe')//字段
            ->view('member m','phone','m.id = fmd.member_id')->where([
                'fmd.diffe'     => ['not in',0],
                'fmd.member_id' => ['not in','149,96']
            ])->select();//
            if ($list)
            {
                $list = $list;
            }
            else
            {
                $list[0]['diffe'] = '无';
                $list[0]['phone'] = '无';

            }
            return $list;

        }
    }